import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_scan_tool/bloc/tool_log/tool_log_bloc.dart';
import 'package:flutter_scan_tool/models/ToolLog.dart';
import 'package:flutter_scan_tool/models/app_theme.dart';
import 'package:flutter_scan_tool/models/tool.dart';
import 'package:flutter_scan_tool/page/contest_tab_header.dart';
import 'package:flutter_scan_tool/utils/date_util.dart';
import 'package:flutter_svg/svg.dart';

class ToolInfoLogPage extends StatefulWidget {
  const ToolInfoLogPage({
    Key? key,
    required this.toolData,
  }) : super(key: key);

  final ToolData toolData;

  @override
  State<ToolInfoLogPage> createState() => _ToolInfoLogPageState();
}

class _ToolInfoLogPageState extends State<ToolInfoLogPage>
    with TickerProviderStateMixin {
  final ScrollController _controller = ScrollController();
  AnimationController? animationController;
  AnimationController? _screenController;

  final String imageUrl =
      "https://img0.baidu.com/it/u=333829888,1801926669&fm=253&fmt=auto?w=722&h=500";

  @override
  void initState() {
    animationController = AnimationController(
        duration: const Duration(milliseconds: 1000), vsync: this);
    _screenController = AnimationController(
        duration: const Duration(milliseconds: 1000), vsync: this);
    animationController?.forward();
    super.initState();
  }

  @override
  void dispose() {
    animationController?.dispose();
    _screenController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: const Color(0xfff2f3f7),
      extendBody: true,
      appBar: AppBar(
        title: Text(
          '工具详情',
          style: AppTheme.appTheme
              .headline1(fontWeight: FontWeight.w100, textColor: Colors.black),
        ),
        leading: IconButton(
          onPressed: () {
            Navigator.pop(context);
          },
          icon: SvgPicture.asset(
            'image/back.svg',
            width: 20,
            height: 20,
            color: Colors.black54,
          ),
        ),
        backgroundColor: const Color(0xfff2f3f7),
        elevation: 0,
      ),
      body: SizedBox(
        width: size.width,
        child: NestedScrollView(
            controller: _controller,
            headerSliverBuilder: (context, innerBoxIsScrolled) {
              return <Widget>[
                SliverList(
                  delegate: SliverChildBuilderDelegate((context, index) {
                    return header(size);
                  }, childCount: 1),
                ),
                SliverPersistentHeader(
                    pinned: true,
                    floating: true,
                    delegate: ContestTabHeader(
                      Container(
                        decoration: const BoxDecoration(
                          borderRadius: BorderRadius.only(
                              bottomRight: Radius.circular(10),
                              bottomLeft: Radius.circular(10)),
                          color: Color(0xfff2f3f7),
                        ),
                        padding: const EdgeInsets.all(10),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Padding(
                              padding: const EdgeInsets.only(left: 5),
                              child: Text(
                                '工具日志信息',
                                style: AppTheme.appTheme.headline1(
                                    textColor: const Color(0xff6875e2),
                                    fontSize: 18,
                                    fontWeight: FontWeight.w300),
                              ),
                            ),
                            InkWell(
                              splashColor: Colors.grey.withOpacity(0.2),
                              focusColor: Colors.transparent,
                              hoverColor: Colors.transparent,
                              highlightColor: Colors.transparent,
                              onTap: () {},
                              child: const Padding(
                                padding: EdgeInsets.only(right: 5),
                                child: Icon(
                                  Icons.arrow_forward,
                                  color: Color(0xff6875e2),
                                ),
                              ),
                            )
                          ],
                        ),
                      ),
                    )),
              ];
            },
            body: toolInfoList()),
      ),
    );
  }

  Widget toolInfoList() {
    return BlocProvider<ToolLogBloc>(
      create: (context) => ToolLogBloc()
        ..add(ToolLoadEvent(toolId: widget.toolData.id.toString())),
      child: BlocBuilder<ToolLogBloc, ToolLogState>(
        builder: (context, state) {
          if (state is ToolLogLoadingState) {
            return const Center(
              child: CircularProgressIndicator(),
            );
          } else if (state is ToolLogLoadSuccessState) {
            if (state.list.isEmpty) {
              return Center(
                  child: Text(
                    '暂无数据',
                    style: AppTheme.appTheme.textStyle(textColor: Colors.black45),
                  ));
            } else {
              return ListView.builder(
                  itemCount: state.list.length,
                  itemBuilder: (context, index) {
                    final int count =
                    state.list.length > 10 ? 10 : state.list.length;
                    final Animation<double> animation =
                    Tween<double>(begin: 0.0, end: 1.0).animate(
                        CurvedAnimation(
                            parent: _screenController!,
                            curve: Interval((1 / count) * index, 1,
                                curve: Curves.fastOutSlowIn)));
                    _screenController?.forward();
                    return logView(state.list[index], animation);
                  });
            }
          } else {
            return const Center(
              child: Text('加载错误'),
            );
          }
        },
      ),
    );
  }

  Container header(Size size) {
    return Container(
      margin: const EdgeInsets.only(left: 12, right: 12),
      child: Stack(
        children: [
          AnimatedBuilder(
            animation: animationController!,
            builder: (context, child) {
              return SlideTransition(
                position: Tween<Offset>(
                    begin: const Offset(1, 0), end: Offset.zero)
                    .animate(CurvedAnimation(
                    parent: animationController!,
                    curve:
                    const Interval(0, 1, curve: Curves.fastOutSlowIn))),
                child: Container(
                  width: double.infinity,
                  height: size.width*0.35,
                  margin: EdgeInsets.only(left: size.width*0.1),
                  decoration: const BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(15)),
                    gradient: LinearGradient(
                      colors: [Color(0xfffc938a), Color(0xfffead93)],
                      begin: Alignment.topRight,
                      end: Alignment.bottomLeft,
                    ),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(10),
                    child: Padding(
                      padding: EdgeInsets.only(left: size.width * 0.2),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          dataInfo(widget.toolData.toolName,
                              fontSize: 20,
                              textColor: Colors.white),
                          const SizedBox(
                            height: 5,
                          ),
                          dataInfo(widget.toolData.toolSpec,
                              textColor: Colors.white),
                          const SizedBox(
                            height: 5,
                          ),
                          dataInfo(widget.toolData.epc,
                              textColor: Colors.white),
                          const SizedBox(
                            height: 5,
                          ),
                          dataInfo(widget.toolData.toolCode,
                              textColor: Colors.white),
                          const SizedBox(
                            height: 5,
                          ),
                          dataInfo(widget.toolData.lockerPosition,
                              textColor: Colors.white),
                        ],
                      ),
                    ),
                  ),
                ),
              );
            },
          ),
          Container(
            margin: const EdgeInsets.only(top: 20),
            child: ClipRRect(
              borderRadius: const BorderRadius.all(Radius.circular(15)),
              child: SizedBox(
                width: size.width * 0.3,
                child: Hero(
                  tag: widget.toolData.id,
                  child: AspectRatio(
                    aspectRatio: 1,
                    child: Image.network(
                      widget.toolData.imgUrl.isEmpty
                          ? imageUrl
                          : widget.toolData.imgUrl,
                      fit: BoxFit.fill,
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget dataInfo(String name,
      {FontWeight fontWeight = FontWeight.w200,
        double fontSize = 18,
        Color textColor = Colors.black}) {
    return Padding(
      padding: const EdgeInsets.only(top: 5),
      child: Text(
        name,
        style: TextStyle(
            fontWeight: fontWeight, fontSize: fontSize, color: textColor),
      ),
    );
  }

  Widget logView(ToolLog toolLogList, Animation<double> animation) {
    return AnimatedBuilder(
      animation: _screenController!,
      builder: (context, child) {
        return FadeTransition(
          opacity: animation,
          child: Transform(
            transform: Matrix4.translationValues(
                0.0, 50 * (1.0 - animation.value), 0.0),
            child: Stack(children: [
              Container(
                width: double.infinity,
                margin: const EdgeInsets.only(left: 10, right: 10, bottom: 10),
                padding: const EdgeInsets.all(10),
                decoration: BoxDecoration(
                  borderRadius: const BorderRadius.only(
                    topRight: Radius.circular(68),
                    topLeft: Radius.circular(8),
                    bottomLeft: Radius.circular(8),
                    bottomRight: Radius.circular(8),
                  ),
                  gradient: const LinearGradient(
                      colors: [Colors.white, Colors.white60],
                      begin: Alignment.topLeft,
                      end: Alignment.bottomRight),
                  boxShadow: <BoxShadow>[
                    BoxShadow(
                        color: Colors.grey.withOpacity(0.2),
                        offset: const Offset(1.1, 1.1),
                        blurRadius: 10.0),
                  ],
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    dataInfo('工具名称:${toolLogList.name}'),
                    dataInfo('当前状态: ${toolLogList.status > 0 ? '出库' : '在库'}'),
                    dataInfo('操作时间:${DateUtil.formDateTime(toolLogList.operateDate)}'),
                    dataInfo('操作人:${toolLogList.operator}')
                  ],
                ),
              ),
              const Positioned(
                top: 10,
                right: 10,
                child: Icon(
                  Icons.circle_outlined,
                  color: Colors.redAccent,
                ),
              ),
            ]),
          ),
        );
      },
    );
  }
}
